//
//  AddressViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/17.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "AddressViewController.h"
#import "AddressModel.h"


@interface AddressViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>


@property (nonatomic, retain) UISearchBar *mySearchBar;
@property (nonatomic, retain) UITableView *addTableV;
@property (nonatomic, retain) NSMutableDictionary *cityDic;

// 排序分组 存的是所有的key
@property (nonatomic, retain) NSMutableArray *sortCityArr;


@property (nonatomic, assign) BOOL active;
@property (nonatomic, assign) BOOL activeScroll;

@property (nonatomic, retain) NSMutableArray *showDataArr;
@property (nonatomic, retain) NSMutableArray *listDataArr;
@property (nonatomic, retain) NSMutableArray *butedDataArr;

@property (nonatomic, retain) UILabel *locationTextLabel;


@end

@implementation AddressViewController
- (void)dealloc
{
    [_mySearchBar release];
    [_addTableV release];
    [_cityDic release];
    [_sortCityArr release];
    [_showDataArr release];
    [_listDataArr release];
    [_butedDataArr release];
    [_locationTextLabel release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"城市选择";
//    self.view.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];

    self.cityDic = [NSMutableDictionary dictionary];

    self.sortCityArr = [NSMutableArray array];
    self.showDataArr = [NSMutableArray array];
    self.listDataArr = [NSMutableArray array];
    self.butedDataArr = [NSMutableArray array];
    
    UIImage *imageleft = [UIImage imageNamed:@"seat_cancel@2x.png"];
    imageleft = [imageleft imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:imageleft style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)] autorelease];
    
    
    // 搜索框
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    self.mySearchBar.delegate = self;
    self.mySearchBar.placeholder = @"请输入城市名称";
    self.mySearchBar.barTintColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    // 透明
//    [self.mySearchBar setSearchBarStyle:UISearchBarStyleMinimal];
    // 去掉mySearchBar边框
//    self.mySearchBar.backgroundImage = [self createImageWithColor:[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1]];
    self.mySearchBar.layer.borderWidth = 0;
    [self.view addSubview:self.mySearchBar];
    [_mySearchBar release];
    

    
    // 列表
    [self getUpdate];
    [self.addTableV reloadData];
    // 去掉多余的分割线
    self.addTableV.tableFooterView = [UIView new];
    
    // 索引背景颜色
    self.addTableV.sectionIndexBackgroundColor = [UIColor clearColor];
    // 设置索引字体颜色
    self.addTableV.sectionIndexColor = NAVG_FONTCOLOR_OFF;
    
    UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 69)];
//    locationView.backgroundColor = [UIColor whiteColor];
    self.addTableV.tableHeaderView = locationView;
    [locationView release];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 25)];
    headView.backgroundColor = [UIColor orangeColor];
    headView.alpha = 0.7f;
    [locationView addSubview:headView];
    [headView release];
    
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, SCREEN_WIDTH - 50, headView.frame.size.height)];
    headLabel.backgroundColor = [UIColor orangeColor];
    headLabel.text = @"当前定位";
    headLabel.textColor = [UIColor whiteColor];
    headLabel.font = [UIFont systemFontOfSize:15.f];
    [headView addSubview:headLabel];
    [headLabel release];
    
    self.locationTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, headView.frame.size.height, SCREEN_WIDTH - 50, locationView.frame.size.height - headView.frame.size.height)];
    self.locationTextLabel.text = @"正在定位";
    self.locationTextLabel.textColor = [UIColor orangeColor];
    self.locationTextLabel.font = [UIFont systemFontOfSize:16.f];
    [locationView addSubview:self.locationTextLabel];
    [_locationTextLabel release];
    
    // 开始定位
    [self startLocation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(location:) name:@"location" object:nil];
    
    
    
    [self addColorChangedBlock:^{
        
        self.mySearchBar.backgroundImage = [self createImageWithColor:[ColorSingleton shareSingleton].sectionBackgroundColor];
        
        locationView.backgroundColor = [ColorSingleton shareSingleton].cellColor;
    }];
}
#pragma mark - 定位相关
- (void)location:(NSNotification *)sender
{
    NSString *str = [sender object];
    self.locationTextLabel.text = str;
}
// color转换成image
- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0,0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark - 搜索框
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
//    [self searchBar:self.mySearchBar textDidChange:nil];
    [self.mySearchBar resignFirstResponder];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
//    NSLog(@"BeginEditing");
    self.activeScroll = NO;
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
//    NSLog(@"EndEditing");
    return YES;
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if ([self.mySearchBar isFirstResponder]) {
        [self.mySearchBar resignFirstResponder];
    }
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
//    NSLog(@"TextDidBeginEditing");
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
//    NSLog(@"TextDidEndEditing");
    
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
//    NSLog(@"selectedScopeButtonIndexDidChange");
}
#pragma mark - 关键字高亮
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
   self.activeScroll = YES;
    [self.showDataArr removeAllObjects];
    [self.butedDataArr removeAllObjects];
    
    if (searchText != nil && searchText.length > 0) {
    
        for (NSString *tempStr in self.listDataArr) {
            if ([tempStr rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0 ) {
                
                [self.showDataArr addObject:tempStr];
                // 关键字高亮
                NSString *keyword = searchText;
                if (0 != keyword.length) {
                    
                    // 设置标签文字
                    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:tempStr];
                    // 获取标红的位置和长度
                    NSRange range = [tempStr rangeOfString:keyword];
                    // 设置标签文字的属性
                    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],   NSFontAttributeName : [UIFont systemFontOfSize:18.f]} range:range];
                    
                    [self.butedDataArr addObject:attrituteString];
                    
                } else {
                    [self.butedDataArr addObject:keyword];
                }

            }
        }
        self.active = YES;
        [self.addTableV reloadData];
    }
    else
    {
        self.active = NO;
        [self.addTableV reloadData];
    }

}
#pragma mark - 列表
- (UITableView *)addTableV
{
    if (nil == _addTableV) {
        self.addTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, self.mySearchBar.frame.origin.y + self.mySearchBar.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - self.mySearchBar.frame.size.height) style:UITableViewStylePlain];
        self.addTableV.delegate = self;
        self.addTableV.dataSource = self;
        [self.addTableV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        self.addTableV.backgroundColor = [UIColor clearColor];
       
        [self.view addSubview:self.addTableV];
        [_addTableV release];
    }
    return _addTableV;
}
// 如果mySearchBar 是第一响应者 table滑动时取消
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.mySearchBar isFirstResponder] && self.activeScroll) {
        [self.mySearchBar resignFirstResponder];
    }
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    self.activeScroll = YES;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, SCREEN_WIDTH - 20, 28)];
    
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:17.f];
    [view addSubview:label];
    [label release];
    
    if (self.active) {
        label.text = @"搜索结果";
    } else {
        if (0 == section) {
            label.text = @"热门搜索";
        } else {
            label.text = [self.sortCityArr objectAtIndex:section];
        }
    }
    
    
    [self addColorChangedBlock:^{
        
        view.backgroundColor = [ColorSingleton shareSingleton].barTintColor;
        label.nightTextColor = [ColorSingleton shareSingleton].cellTitleColor;
        label.normalTextColor = [ColorSingleton shareSingleton].cellTitleColor;
    }];
    
    return view;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.active) {
        return @"搜索结果";
    } else {
        
        if (0 == section) {
            return @"热门搜索";
        }
    }
    return [self.sortCityArr objectAtIndex:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.active) {
        return (NSInteger)1;
    }
    return self.sortCityArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.active) {
        return self.showDataArr.count;
    }
    return [[self.cityDic objectForKey:[self.sortCityArr objectAtIndex:section]] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *cellStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    
    if (self.active) {
        
        cell.textLabel.attributedText = [self.butedDataArr objectAtIndex:indexPath.row];
    } else {
        NSString *key = [self.sortCityArr objectAtIndex:indexPath.section];
        NSMutableArray *arr = [self.cityDic objectForKey:key];
        AddressModel *addMod = [arr objectAtIndex:indexPath.row];
        
        cell.textLabel.text = addMod.name;

        cell.textLabel.textColor = [UIColor colorWithRed:0.08 green:0.08 blue:0.08 alpha:1];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    
    [self addColorChangedBlock:^{
        
        cell.contentView.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        cell.contentView.normalBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        
        // 改变tableview线的颜色
        self.addTableV.separatorColor = [ColorSingleton shareSingleton].cellLineColor;
        
//        cell.textLabel.textColor = [ColorSingleton shareSingleton].cellTitleColor;
        
        cell.textLabel.nightTextColor = [ColorSingleton shareSingleton].cellTitleColor;
        cell.textLabel.normalTextColor = [ColorSingleton shareSingleton].cellTitleColor;
    }];
    

    return cell;
}
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.sortCityArr];
    [arr removeObject:@"HOT"];
    return arr;
}
#pragma mark 改变城市
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", indexPath.row);
    // 选中时有置灰效果, 离开时消失选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 搜索时存储搜索结果
    if (self.active) {
        NSString *cityName = [self.showDataArr objectAtIndex:indexPath.row];
        NSString *cityId = nil;
        for (NSString *key in self.cityDic) {
            for (AddressModel *addMod in [self.cityDic objectForKey:key]) {
                if ([cityName isEqualToString:addMod.name]) {
                    cityId = addMod.cityid;
                }
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:cityName forKey:@"cityName"];
        [[NSUserDefaults standardUserDefaults] setObject:cityId forKey:@"cityid"];
    } else {
        
        NSString *key = [self.sortCityArr objectAtIndex:indexPath.section];
        NSMutableArray *arr = [self.cityDic objectForKey:key];
        AddressModel *addMod = [arr objectAtIndex:indexPath.row];
        
        [[NSUserDefaults standardUserDefaults] setObject:addMod.name forKey:@"cityName"];
        [[NSUserDefaults standardUserDefaults] setObject:addMod.cityid forKey:@"cityid"];
    }
    // 发送通知 首页刷新
    [[NSNotificationCenter defaultCenter] postNotificationName:@"homeRefurbish" object:nil];

    [self dismissViewControllerAnimated:YES completion:^{

    }];
}
#pragma mark - 获取数据
- (void)getUpdate
{
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/citylist.json?source=%d&version=%d", URL_SOURCE, URL_VERSION];
    [AppTools getAFNet:url block:^(id result) {

        [self.cityDic removeAllObjects];
        [self.sortCityArr removeAllObjects];
        [self.listDataArr removeAllObjects];
        
        NSMutableDictionary *bigDic = result;

        
        
        NSMutableArray *bigArr = [bigDic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in bigArr) {
            
            NSMutableArray *arr = [NSMutableArray array];
            for (NSMutableDictionary *dicTemp in [dic objectForKey:@"citylist"]) {
                

                AddressModel *addMod = [AddressModel modelWithDictionary:dicTemp];
                [arr addObject:addMod];
               
            
            }
             [self.cityDic setObject:arr forKey:[dic objectForKey:@"one"]];
            
        }
        
        // 排序
        self.sortCityArr = [NSMutableArray arrayWithArray:self.cityDic.allKeys];
        [self.sortCityArr sortUsingSelector:@selector(compare:)];
        [self.sortCityArr removeObject:@"HOT"];
        
        for (NSString *key in self.cityDic) {
            for (AddressModel *addMod in [self.cityDic objectForKey:key]) {
                [self.listDataArr addObject:addMod.name];
            }
        }
        
   
        [self.sortCityArr insertObject:@"HOT" atIndex:0];
        
        [self.addTableV reloadData];
    
        
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
            [self dismissViewControllerAnimated:YES completion:^{
                
                
            }];
        }];
    }];
}
#pragma mark - 左按钮
- (void)leftAction
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
//- (UISearchController *)mysearch {
//    
//    if (!_mysearch) {
//        
//        self.mysearch = [[UISearchController alloc] initWithSearchResultsController:nil];
//        self.mysearch.searchBar.frame = CGRectMake(0, 64, SCREEN_WIDTH, 44);
//        self.mysearch.searchResultsUpdater = self;
//        self.mysearch.dimsBackgroundDuringPresentation = NO;
//        self.mysearch.hidesNavigationBarDuringPresentation = NO;
//        [self.mysearch.searchBar setPlaceholder:@"搜索列表"];
//        [self.mysearch.searchBar setBarTintColor:[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1]];
//        // 样式: 半透明
//        //        [self.mysearch.searchBar setSearchBarStyle:UISearchBarStyleMinimal];
//        //        self.mysearch.searchBar
//        //        self.mysearch.searchBar.frame = CGRectMake(self.mysearch.searchBar.frame.origin.x, self.mysearch.searchBar.frame.origin.y, self.mysearch.searchBar.frame.size.width, 44.0);
//        
////        self.movieTableV.tableHeaderView = self.mysearch.searchBar;
//        
//        //        [self.mysearch.searchBar sizeToFit];
//        
//    }
//    
//    return _mysearch;
//}
//search过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSLog(@"+++ %@", NSStringFromCGRect(searchController.searchBar.frame));
//    NSString *searchString = [self.mysearch.searchBar text];
//    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS [c] %@", searchString];

 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
